package com.spoplar.topics;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;




public class JMSProducer {
	public static final String USERNAME =ActiveMQConnection.DEFAULT_USER ;  //用户名
	public static final String PASSWORD =ActiveMQConnection.DEFAULT_PASSWORD ; //密码
	public static final String BROKER_URL =ActiveMQConnection.DEFAULT_BROKER_URL ; //消息总线

	public static final int SENDNUMS = 10;

	public static void main(String[] args) throws JMSException {
		
		 ConnectionFactory connectFactoy;
		 Connection connection = null;
		 Session session = null;
		 Destination destination;
		 MessageProducer  messageProducer;
		 
		 connectFactoy= new ActiveMQConnectionFactory(  //创建连接工厂
				JMSProducer.USERNAME, 
				JMSProducer.PASSWORD, 
				JMSProducer.BROKER_URL
				);
		 try {
			connection = connectFactoy.createConnection(); //创建连接
			session = connection.createSession(Boolean.TRUE,Session.AUTO_ACKNOWLEDGE);//会话（事务，确认方式）
			destination=session.createTopic("topic 1");
			messageProducer =session.createProducer(destination);
			sendMsg(session,messageProducer);
			session.commit();
		} catch (JMSException e) {
			e.printStackTrace();
		}finally{
			if(session!=null){
				session.close();
			}
			if(connection !=null){
				connection.close();
			}
		}
		 
	
	}
	public static  String sendMsg (Session session,MessageProducer messageProducer) throws JMSException {
		for(int i=0;i<JMSProducer.SENDNUMS;i++){
			TextMessage txMessage=session.createTextMessage("消息" + i);
			System.out.println("发送消息："+i);
			messageProducer.send(txMessage);
		}
		return null;
	}
}
